import time
import threading
from datetime import datetime, timedelta


class ReadWriteLock:
    def __init__(self):
        self._read_ready = threading.Condition(threading.Lock())
        self._readers = 0

    def acquire_read(self):
        with self._read_ready:
            while self._readers < 0:
                self._read_ready.wait()
            self._readers += 1

    def release_read(self):
        with self._read_ready:
            self._readers -= 1
            if not self._readers:
                self._read_ready.notifyAll()

    def acquire_write(self):
        with self._read_ready:
            while self._readers != 0:
                self._read_ready.wait()
            self._readers = -1

    def release_write(self):
        with self._read_ready:
            self._readers = 0
            self._read_ready.notifyAll()


class Cache:
    def __init__(self):
        self.lock = threading.RLock()
        self.cache = {}
        self.cache_time = {}

    def get(self, query):
        with self.lock:
            if query in self.cache:
                if datetime.now() < self.cache_time[query] + timedelta(minutes=10):
                    return 0, self.cache[query]
                else:
                    return -1, self.cache[query]
            else:
                return 1, None

    def set(self, query, result):
        with self.lock:
            self.cache[query] = result
            self.cache_time[query] = datetime.now()

# 使用示例


def worker(cache):
    # 查询缓存
    res, data = cache.get("query")
    print(f"Worker get: ({res}, {data})")

    if res == 1 or res == -1:
        # 设定缓存
        cache.set("query", "result")


if __name__ == '__main__':
    cache = Cache()

    for i in range(3):
        threading.Thread(target=worker, args=(cache,)).start()

    # 让工作线程有机会运行
    time.sleep(2)
